<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="number">
              <a-input v-model="model.number" placeholder="请输入编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="应收金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="amountReceivable">
              <a-input-number v-model="model.amountReceivable" placeholder="请输入应收金额"  style="width: 100%" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="回款状态" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="state">
              <j-dict-select-tag type="list" v-model="model.state" dictCode="receivables_state"  placeholder="请选择回款状态"  disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="预计回款日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="estimatedCollectionDate">
              <j-date placeholder="请选择预计回款日期" v-model="model.estimatedCollectionDate" :disabled='isSK' style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联客户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerId">
              <JSelectMultiUser  v-model="model.customerId" :query-config="selectUserQueryConfig" :url="kehuurl"  @change="kehuChange" :disabled='isAdd'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="关联合同" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="orderContractId">
              <relatecontract displayKey="name" v-model="model.orderContractId" :query-config="hetongConfig" :multiple="false"
                              :url="hetongurl" v-if="customerIdShow" @change="hetongChange" :disabled='isAdd'></relatecontract>
              <span v-else>无</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="回款类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <j-dict-select-tag type="list" v-model="model.type" dictCode="receivables_type" placeholder="请选择类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="directorIds" >
              <j-select-user-by-dep v-model="model.directorIds" :multi="true" :disabled='isSK'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if='isShow'>
            <a-form-model-item label="协同人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="collaboratorIds" >
              <j-select-user-by-dep v-model="model.collaboratorIds" :multi="true" :disabled='isSK'/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-else>
            <a-form-model-item label="关联应收款" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="receivablesList">
              <div>
                <a-button type="primary" @click="openYingshoukuan" :disabled=" this.addAmount == 0 || this.addAmount < 0">添加应收款</a-button>
                {{ `( 合同金额:  ${contractAmount}  ,可添加金额:  ${addAmount})` }}
              </div>
              <div>
                <a-table
                  v-if="yingshoukuanTableShow"
                  ref="yingshoukuantable"
                  size="middle"
                  :scroll="{x:true}"
                  rowKey="id"
                  bordered
                  :columns="yingshoukuanColumns"
                  :pagination="false"
                  :dataSource="yingshoukuanTable">
                  <template slot="state" slot-scope="text,record">
                    <j-dict-select-tag type="list" v-model="record.state" disabled dictCode="receivables_state" />
                  </template>
                  <template slot="type" slot-scope="text,record">
                    <j-dict-select-tag type="list" v-model="record.type" disabled dictCode="receivables_type" />
                  </template>
                  <span slot="operation" slot-scope="text, record,index" >
                    <a @click="yingshoukuanTableEdit(record)" v-if='record.id == null'>编辑</a>
                    <a-divider type="vertical" v-if='record.id == null' />
                    <a @click="yingshoukuanTableDel(index)" v-if='record.id == null'>删除</a>
                     <a style='color: #c5c5c5' v-else>不可编辑</a>
                  </span>
                </a-table>
                <span>注：已存在的应收款此页面不可编辑</span>
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <yingshoukuanModal ref="yingshoukuanModel" @ok="yingshoukuanOK"></yingshoukuanModal>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { validateDuplicateValue } from '@/utils/util'
  import relatecontract from '@/components/jeecgbiz/relatecontract/index'
  import receivables from '@/components/jeecgbiz/receivables/index'
  import JSelectUserByDep from '@/components/jeecgbiz/JSelectUserByDepCustom'
  import JSelectMultiUser from '@comp/jeecgbiz/JSelectMultiUserCustom'
  import JSelectUserByDepModalCustom from '@/components/jeecgbiz/modal/JSelectUserByDepModalCustom'
  import JSelectUserByDepCustom from '@comp/jeecgbiz/JSelectUserByDepCustom'
  import yingshoukuanModal from './AddReceivablessModal'
  import type from '@views/exception/type'
  import JSelectBizComponentModal from '@/components/jeecgbiz/relatecontract/JSelectBizComponentModal'
  import { ajaxGetDictItems } from '@api/api'


  export default {
    name: 'ReceivablesForm',
    components: {
      JSelectUserByDep,
      JSelectMultiUser,
      JSelectUserByDepModalCustom,
      relatecontract,
      receivables,
      JSelectUserByDepCustom,
      yingshoukuanModal,
      JSelectBizComponentModal,


    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
    },
    watch: {
      'model.customerId': {
        deep: true,
        handler(newValue, oldValue) {
          if (!newValue || newValue !== oldValue) {
            this.customerIdShow = false
          }
          if (newValue) {
            this.$nextTick(() => {
              this.customerIdShow = true
              this.kehuurl = '/customer/customer/lists?filed=2&id=' + newValue
              if (this.model.orderContractId) {
                this.hetongurl = '/contractorder/contractOrder/lists?customerId=' + newValue + '&id=' + this.model.orderContractId
              } else {
                this.hetongurl = '/contractorder/contractOrder/lists?customerId=' + newValue
              }
            })
          }
        }
      },
      'model.orderContractId': {
        deep: true,
        handler(newValue, oldValue) {
          if (!newValue || newValue !== oldValue) {
            this.orderIdShow = false
          }
          if (newValue) {
            this.$nextTick(() => {
              this.orderIdShow = true
              this.yingshoukuanurl = '/sys/common/queryByReceivables?id=' + newValue
            })
          }
        }
      },
      yingshoukuantable: {
        deep: true,
        handler(newValue, oldValue) {
          console.log('yingshoukuantable的变化', newValue)
          this.yingshoukuanTable = newValue
          this.TotalAmount()
        },
      },

    },
    data () {
      return {
        newTempArr:[],
        yingshoukuanTableShow: false,//应收款表格显隐
        yingshoukuanTable: [],
        yingshoukuanCount: 1, //应收款计数器
        contractAmount:0,//合同全部金额
        uncollectedAmount:0,//合同未收金额
        shishouAmount:0,//应收款实收金额
        addAmount:0,// 可添加金额
        isAdd:false,
        isSK:false,
        isShow:false,
        customerIdShow: false,
        kehuurl: '/customer/customer/lists?filed=2',
        // 客户
        selectUserQueryConfig: [
          { key: 'phone', label: '电话' }
        ],
        //合同
        hetongurl: '/contractorder/contractOrder/list?filed=2'+'&customerId=' ,
        hetongConfig: [
          { key: 'number', label: '合同编号' }
        ],
        //应收款
        yingshoukuanurl:'/sys/common/queryByReceivables?id=',
        yingshoukuanConfig: [
          {key: 'number', label: '应收款编号'},
        ],
        //应收款表格配置
        yingshoukuanColumns: [
          {
            title: '应收金额',
            dataIndex: 'amountReceivable',
            key: 'amountReceivable'
          },
          {
            title: '回款状态',
            dataIndex: 'state',
            key: 'state',
            scopedSlots: { customRender: 'state' }
          },
          {
            title: '预计回款日期',
            dataIndex: 'estimatedCollectionDate',
            key: 'estimatedCollectionDate'

          },
          {
            title: '回款类型',
            dataIndex: 'type',
            key: 'type',
            scopedSlots: { customRender: 'type' }
          },
          {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            width: 100,
            fixed: 'right',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        model:{
         },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          customerId: [
            { required: true, message: '请选择关联客户!' }
          ],
          orderContractId: [
            { required: true, message: '请选择关联合同!' }
          ],
          number: [
            { required: true, message: '请输入产品编号!'},
          ],
          state: [
            { required: true, message: '请选择回款状态!'},
          ],
          estimatedCollectionDate: [
            { required: true, message: '请选择预计回款日期!'},
          ],
          directorIds: [
            { required: true, message: '请选择负责人!'},
          ],
          amountReceivable: [
            { required: true, message: '请输入应收金额!'},
            { pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'},
           ],
        },
        url: {
          add: "/receivables/receivables/add",
          edit: "/receivables/receivables/edit",
          queryById: "/receivables/receivables/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      kehuChange(e) {
        console.log("选择客户按钮",e)
        this.customerIdShow = false
        this.model.contactsIds = ''
      },
      hetongChange(e) {
        console.log("选择合同按钮",e)
        this.orderIdShow = false
        let orderContractIds = e
        getAction('/contractorder/contractOrder/queryById?id='+ orderContractIds ).then(res => {
          if (res.success) {
            let tempArr = res.result
            console.log('合同list',tempArr)
            this.contractAmount = Number(tempArr.map(e=>{
              return e.contractAmount
            }))
            console.log('合同金额',this.contractAmount)
            this.uncollectedAmount = Number(tempArr.map(e=>{
              return e.uncollectedAmount
            }))
            console.log('合同未收金额',this.uncollectedAmount)
          }
        })
        getAction('/sys/common/queryReceivables?id='+ orderContractIds ).then(res => {
          if (res.success) {
            let TempArr = res.result
            console.log('关联合同的所有应收款',TempArr)
            let yskIdTemp = TempArr.map((e=>{
              return  e.id
            }))
            let yskId= yskIdTemp.toString()
            this.model.ids = yskId
            let TempKey = []
            TempArr.map((item) => {
              TempKey.push(Object.assign({}, item, { key: this.yingshoukuanCount }))
              this.yingshoukuanCount +=1
            })
            if(TempArr == 1 ){
              let ssAmountSum = TempArr.map(e=>{
                return  e.actualAmount
              })
              this.shishouAmount = ssAmountSum // 该合同关联的所有应收款的实收金额
              console.log('该合同关联的所有应收款的实收金额',this.shishouAmount)
            }else{
              let ssAmountSum = TempArr.reduce((ssAmountSum, e) => {
                return ssAmountSum += e.actualAmount
              }, 0)
              this.shishouAmount = ssAmountSum // 该合同关联的所有应收款的实收金额
              console.log('该合同关联的所有应收款的实收金额',this.shishouAmount)
            }
            this.yingshoukuanTableShow = true
            this.yingshoukuanTable = TempArr
            this.TotalAmount()
            // getAction('/sys/common/isAdmin' ).then(res => {
            //     if(res == true){//判断当前登录id是否为管理员
            //       this.yingshoukuanTableShow = true
            //       this.yingshoukuanTable = TempArr
            //       console.log('Tableeeeeeeeeeeeeeeeeee',this.yingshoukuanTable)
            //     } else{
            //       let userID = JSON.parse(localStorage.getItem('pro__Login_Userinfo'))
            //       let dlId = userID.value.id //获取当前登录账户id
            //       console.log('dlIddddddddddddddddddddddd',dlId)
            //       console.log('TempKeyyyyyyyyyyyyyyyyy',TempKey)
            //       TempKey.forEach(e=>{
            //        if( e.customerId.includes(dlId)  ||  e.directorIds.includes(dlId)  ){
            //          this.yingshoukuanTableShow = true
            //          console.log('eeeeeeeeeeeeeeeeeeeeee',e)
            //          this.yingshoukuanTable.push(e)
            //          this.yingshoukuanCount += 1
            //         }
            //         else{
            //           this.yingshoukuanTableShow = false
            //        }
            //       })
            //     }
            //   })
          }
        })
      },
      TotalAmount() {
        let amountSum = this.yingshoukuanTable.reduce((amountSum, e) => {
          return amountSum += e.amountReceivable
        }, 0)
        this.model.amountReceivable = amountSum// 该合同关联的所有应收款的金额
        //可添加金额计算 = 合同未收金额 - 该合同关联的所有应收款的金额 + 该合同关联的所有应收款的实收金额
        this.addAmount = this.uncollectedAmount - this.model.amountReceivable + this.shishouAmount
      },
      //应收款回执
      yingshoukuanOK(res) {
        console.log('add应收款返回数据', res)
        const { yingshoukuanCount, yingshoukuanTable } = this
        if (res.key) {
          //编辑的情况
          const yingshoukuanTable = [...this.yingshoukuanTable]
          let target = yingshoukuanTable.find((item) => item.key == res.key)
          target = Object.assign(target, res)
          this.yingshoukuanTable = yingshoukuanTable
        }
        else {
          //新增的情况
          let newData = Object.assign(res, { key: yingshoukuanCount })
          this.yingshoukuanTable = [...this.yingshoukuanTable, newData]
          this.yingshoukuanCount += 1
        }
        //这里要区分是编辑还是新增的回传
        this.yingshoukuanTable.length > 0 ? this.yingshoukuanTableShow = true : this.yingshoukuanTableShow = false
        console.log('回款单表格实时动态', this.yingshoukuanTable)
        this.TotalAmount()
      },
      //应收款按钮新增
      openYingshoukuan() {
        this.$refs.yingshoukuanModel.add()
        this.$refs.yingshoukuanModel.passON(this.addAmount)
      },
      //应收款表格编辑
      yingshoukuanTableEdit(record) {
        console.log('record', record)
        this.$refs.yingshoukuanModel.edit(record)
        this.$refs.yingshoukuanModel.passONEdit(this.addAmount + record.amountReceivable)
      },
      //应收款表格删除
      yingshoukuanTableDel(index) {
        console.log('index', index)
        this.yingshoukuanTable.splice(index, 1)
        this.TotalAmount()
      },
      add() {
        this.edit(this.modelDefault)
        this.isShow = false
        this.isAdd = false
      },
      edit(record) {
        this.isShow = true
        this.isAdd = true
        this.model = Object.assign({}, record)
        let count = 0
        let yingshoukuancount = 0
        console.log('==============record', record)
        //应收款
        if (record.receivablesList) {
          record.receivablesList.map(res => {
            res.key = yingshoukuancount += 1
            return res
          })
          this.yingshoukuanTable = record.receivablesList
        }
        this.visible = true
      },
      submitForm() {
        console.log('this.model', this.model)
        this.model.receivablesList = this.yingshoukuanTable
        const that = this
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
    }
  }
</script>